package com.taijihuabao.common.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.taijihuabao.modules.entity.ReimbursementEntity;
import com.taijihuabao.modules.service.ReimbursementService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 报销数据导入的监听器
 * @title: ExpenseExcelLister
 * @Author luoxianan
 * @Date: 2022/1/11 14:24
 * @Version 1.0
 */
@Slf4j
public class ExpenseExcelLister extends AnalysisEventListener<ReimbursementEntity> {
    /**
     *  每隔20条存储数据库
     */
    private static final int BATCH_COUNT = 20;
    List<ReimbursementEntity> expenseEntityList = new ArrayList<>();
    /**
     * 是Service也行
     */
    private ReimbursementService reimbursementService;
    public ExpenseExcelLister(ReimbursementService reimbursementService){
        this.reimbursementService = reimbursementService;
    }
    @Override
    public void invoke(ReimbursementEntity data, AnalysisContext context) {
        expenseEntityList.add(data);
        if (expenseEntityList.size() >= BATCH_COUNT){
            saveExpense();
            expenseEntityList.clear();
        }
    }
    private void saveExpense(){
        for (ReimbursementEntity expenseEntity:expenseEntityList){
            reimbursementService.insertExpense(expenseEntity);
        }
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveExpense();
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        super.invokeHeadMap(headMap, context);
        log.info("表头+"+headMap);
    }
}
